package org.jeecg.modules.compilation.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class WordUtil {

    private static   String handleContent(String text){
        String finallyText ;
        //查看是否有 附件： ，如果有附则，则会有表格，反之读整偏文章即可
        if( text.lastIndexOf("附件：") != -1){
            finallyText = text.substring( 0, text.lastIndexOf("附件：") );
            finallyText += handleAnnex( text.substring( text.lastIndexOf("附件：") ) );
            finallyText += handleTail( text );
            return finallyText;
        }

        return text.substring(0,text.lastIndexOf("印发") + 2);
    }

    private static String handleAnnex(String text){
        Pattern pattern = Pattern.compile("[0-9]+\\.");
        Matcher matcher = pattern.matcher(text);

        String textTmp =  text.substring(0,3) + (char) 10;
        //最后一个 数字. 的位置
        int count = 0;
        String maxNum = "0";
        while (matcher.find()) {

            count = matcher.start();
            log.info("正则查找到位于：{}",count);
            String tmp = text.substring(count);

            String tmpNum = "";
            int i;
            //计算序号
            for(  i = 0 ; tmp.charAt(i) != '.'  ; i++ ){
                System.out.println(tmp.charAt(i));
                tmpNum += tmp.charAt(i) + "";
            }
            //序号前后是否满足条件
            //                 有一种情况未解决：就是当读下来的内容为
            //                    1.招聘需求报告（模板）
            //                    2.招聘需求统计表
            //                    3.招聘工作纪实表
            //                    4 .招聘岗位须填省局（公司）统一发布的标准岗位名称，不得出现字眼差异。
            //                    已经按顺序前面表好按顺序，但是4.的内容并不属于读取范围内容
            if( Integer.parseInt(tmpNum) - Integer.parseInt(maxNum) != 1){
                break;
            }
            maxNum = tmpNum;
            int j = i + 1;
            //查找序号结束位置
            for (  ;  ; j++ ) {
                if((int) tmp.charAt(j) == 10 || (int) tmp.charAt(j) == 13){
                    break;
                }
            }
            textTmp += maxNum  + tmp.substring(i,j) + (char) 10;
        }
        //如果附件不存在序号状态
        if ( textTmp.equals("附件：" + (char)10 ) ){
            for( int i = 3 ; ; i++){
                char lokk = text.charAt(i);
                if( (int) text.charAt(i) == 10 || (int) text.charAt(i) == 13){
                    textTmp +=  text.substring( 3 , i );
                    break;
                }
            }
        }

        return textTmp + (char) 10;
    }

    private static String handleTail(String text){
        //查找‘分送’位置
        Integer sendFor = text.lastIndexOf("分送");
        //查找'抄送'位置
        Integer copyFor = text.lastIndexOf("抄送");
        //查找‘广东省中山市烟草专卖局（公司）办公室’位置
        Integer companyLabelOne = text.lastIndexOf("广东省中山市烟草专卖局（公司）办公室");
        //查找‘中山市烟草专卖局(公司)办公室’位置
        Integer companyLabelTwo = text.lastIndexOf("中山市烟草专卖局(公司)办公室");
        //查找’印发‘位置
        int printAndDistribute = text.lastIndexOf("印发") + 2;
        return (char)10 + text.substring(  sendFor != -1 ? sendFor : copyFor != -1 ? copyFor : companyLabelOne!= -1 ? companyLabelOne : companyLabelTwo,printAndDistribute);
    }

//    public static String  handleWordContent(String path){
//
//        String suffixName = path.substring(path.lastIndexOf("."));//从最后一个.开始截取。截取fileName的后缀名
//        try {
//            File file = new File(path);
//            FileInputStream fs = new FileInputStream(file);
//            String text ;
//            if(suffixName.equals(".doc")){//doc
//                WordExtractor re = new WordExtractor(fs);
//                text = re.getText();//获取word中的文本内容
//                re.close();
//            }else {//docx
//                XWPFDocument doc = new XWPFDocument(fs);
//                XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
//                text = extractor.getText();//获取word中的文本内容
//                extractor.close();
//                fs.close();
//            }
//
//
//            text.replace("\r","\n");
//            int flag = 1;
//            for( int i = 0 ; i < text.length(); i++ ) {
//
//                if ( flag == 1 && ( (int) text.charAt(i) == 10 ||  (int) text.charAt(i) == 13 ) ) {
//                    for ( int j = i ; j < text.length() ; j++ ) {
//                        log.info( "{}" ,(int) text.charAt(j) );
//                        if( (int) text.charAt(j) == 10 || (int) text.charAt(j) == 13 )
//                           continue;
//                        text = text.substring(j);
//                        i = 0;
//                        break;
//                    }
//                }
//                flag = 0;
//
//                if ( (int) text.charAt(i) == 13 || (int) text.charAt(i) == 10 ) {
//                    for ( int k = i ; k <  text.length() ; k++ ) {
//                        if ( (int) text.charAt( k ) == 10 || (int) text.charAt( k ) == 13 )
//                            continue;
//                        text = text.substring( 0 , i ) + "\n" + text.substring( k );
//                        break;
//                    }
//                }
//            }
//            return text;
//        }catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//
//    }


    public static String  handleWordContent(String path) {
        String suffixName = path.substring(path.lastIndexOf("."));//从最后一个.开始截取。截取fileName的后缀名
        try {
            File file = new File(path);
            FileInputStream fs = new FileInputStream(file);
            String text;
            if (suffixName.equals(".doc")) {//doc
                return readLineFromWordDoc(path);
            }else {
                return readLineFromWordDocx(path);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static String readLineFromWordDoc(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        HWPFDocument document = new HWPFDocument(fis);
        WordExtractor extractor = new WordExtractor(document);
        StringBuilder textBuilder = new StringBuilder();



        String[] paragraphs = extractor.getParagraphText();
        for (String paragraph : paragraphs) {
            if (paragraph != null && !paragraph.isEmpty()) {
                textBuilder.append(paragraph.trim());
                textBuilder.append("\n");

                // 检查是否到达指定行号
                if (textBuilder.toString().split("\n").length == 1) {
                    break;
                }
            }
        }

        fis.close();
        document.close();

        return textBuilder.toString();
    }


    public static String readLineFromWordDocx(String filePath) throws IOException {
        FileInputStream fis = new FileInputStream(filePath);
        XWPFDocument document = new XWPFDocument(fis);
        StringBuilder textBuilder = new StringBuilder();

        int lineCount = 0;
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            String paragraphText = paragraph.getText();
            if (paragraphText != null && !paragraphText.isEmpty()) {
                // 根据段落文本进行行数计算
                int paragraphLines = paragraphText.split("\n").length;
                lineCount += paragraphLines;
            }
        }


        for (XWPFParagraph paragraph : document.getParagraphs()) {
            String paragraphText = paragraph.getText();
            if (paragraphText != null && !paragraphText.isEmpty()) {
                textBuilder.append(paragraphText.trim());
                textBuilder.append("\n");

                // 检查是否到达指定行号
                if (textBuilder.toString().split("\n").length == lineCount) {
                    break;
                }
            }
        }

        fis.close();
        document.close();

        return textBuilder.toString();
    }

    public static void main(String [] args) throws IOException {
//          System.out.println(readWord("C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\document\\41.中烟办〔2021〕27号（广东省中山市烟草专卖局关于印发《中山市烟草专卖局（公司）保密管理规定》的通知）.doc"));
//        System.out.println(
//                handleWordContent("C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\document\\41.中烟办〔2021〕27号（广东省中山市烟草专卖局关于印发《中山市烟草专卖局（公司）保密管理规定》的通知）.doc")
//        );

//        System.out.println(
//                readLineFromWordDoc("C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\document\\86.中烟人〔2022〕30号（广东省中山市烟草专卖局关于印发《中山市烟草专卖局（公司）员工晋升管理办法》的通知）.doc")
//        );

//        System.out.println(
//                readLineFromWordDocx("C:\\Users\\Lenovo\\Desktop\\烟草局制度汇编环境部署\\document\\187.中烟法〔2019〕14号（广东省中山市烟草专卖局印发《中山市烟草专卖重大执法决定法制审核制度》的通知）.docx")
//        );



    }
}
